<?php
class ZendX_Sphinx
{
    static protected $_default = NULL;
    static protected $_instance = NULL;
    protected $_client = NULL;

    public function __construct() {
        $this->_client = Zend_Registry::get('SphinxClient');
    }

    /**
     * @return ZendX_Sphinx
     */
    static public function getInstance()
    {
        if (NULL === self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    static public function setDefaultClient(SphinxClient $client)
    {
        self::$_default = $client;
    }

    public function __call($name, $arguments)
    {
        call_user_func_array(array($this->_client, $name), $arguments);
    }

    /**
     * @param string $index
     * @return ZendX_Sphinx_Request
     */
    static public function Query($index = NULL, $field = NULL)
    {
        return new ZendX_Sphinx_Request($index, $field);
    }

    /**
     * @throws Exception
     * @param ZendX_Sphinx_Request $request
     * @param string $wrapper
     * @return ZendX_Sphinx_Result
     */
    public function request(ZendX_Sphinx_Request $request, $wrapper = 'ZendX_Sphinx_Result')
    {
        $request->apply($this);
        $Result = $this->_client->Query($request->getSearchContent(), $request->getSearchIndex());
        if ($Result === FALSE) {
            die('Sphinx error: ' . $this->_client->GetLastError());
        }
        if (!empty($Result['error'])) {
            die('Sphinx error: ' . $Result['error']);
        }
        $data = array();

        if (isset($Result['matches']))
            foreach ($Result['matches'] as $key => $value) {
                $value['attrs']['id'] = $key;
                $data[] = $value['attrs'];
            }

        return new $wrapper($data, $Result['total_found']);
    }

}
